/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Global Trust Authority is licensed under the Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *     http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#![allow(unused_imports)]
use crate::entities::{
    cert_constants::{CertificateType, ValidCode},
    cert_info,
    cert_request::{AddCertRequest, DeleteRequest, DeleteType, QueryInfo, UpdateCertRequest},
    cert_resp_info::CertRespInfo,
    cert_response::{AddCertResponse, DeleteResponse, QueryResponse},
    cert_revoke_list_info::CertRevokeListInfo,
    cert_revoked_list, crl_info,
};
use crate::error::cert_error::{CertError, CertVerifyError};
use crate::repositories::cert_repository::CertRepository;
use crate::utils::utils::{
    asn1_time_to_timestamp, generate_cert_id, get_cert_digest, get_cert_issuer_name, get_cert_serial_number,
    get_cert_signature, get_cert_subject_name, get_crl_issuer_name, get_crypto_operations, get_revoke_cert_signature,
    get_signature, parse_cert_content, parse_crl_content, verify_cert, verify_cert_time, verify_signature,
};
use actix_web::http::StatusCode;
use actix_web::web::Data;
use actix_web::HttpResponse;
use chrono::NaiveDateTime;
use common_log::{debug, error, info};
use config_manager::types::CONFIG;
use futures::stream::{self, StreamExt};
use key_management::api::{impls::DefaultCryptoImpl, CryptoOperations};
use openssl::asn1::{Asn1Time, Asn1TimeRef};
use openssl::error::ErrorStack;
use openssl::hash::MessageDigest;
use openssl::nid::Nid;
use openssl::sign::Verifier;
use openssl::x509::{ReasonCode, X509Crl, X509};
use rdb::get_connection;
use sea_orm::{ActiveValue, DatabaseConnection, DatabaseTransaction, TransactionTrait, IntoActiveModel};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::BTreeMap;
use std::sync::Arc;
use uuid::Uuid;
use validator::{Validate, ValidationError};

pub struct CertService;

impl CertService {
    pub(crate) const MAX_NUMBER_OF_QUERIES: usize = 100;

    async fn query_crl_info(
        db: Data<Arc<DatabaseConnection>>,
        ids: &Option<Vec<String>>,
        user_id: &str,
    ) -> Result<HttpResponse, CertError> {
        let crl_ids = ids.clone().unwrap_or_default();
        let result = if crl_ids.is_empty() {
            CertRepository::query_user_crl_info(&db, user_id).await
        } else {
            CertRepository::query_user_crl_info_by_ids(&db, crl_ids, user_id).await
        };
        match result {
            Ok(crl_infos) => {
                let query_response = json!({
                    "crls": crl_infos.into_iter()
                            .map(|crl_info| CertRevokeListInfo {
                                crl_id: crl_info.crl_id,
                                crl_name: crl_info.name,
                                crl_content: String::from_utf8_lossy(&crl_info.crl_content).to_string(),
                            }).collect::<Vec<CertRevokeListInfo>>(),
                });
                Ok(HttpResponse::Ok().json(query_response))
            },
            Err(e) => {
                error!("Query crl_info error: {:?}", e);
                Err(CertError::DbError(format!("Query crl_info error: {}", e.to_string())))
            },
        }
    }



    /// Validates input parameters for certificate queries.
    ///
    /// # Arguments
    /// * `ids` - Optional vector of certificate IDs to validate.
    /// * `cert_type` - Optional certificate type to validate.
    ///
    /// # Returns
    /// `Ok(())` if validation passes, `Err(CertError)` if validation fails.
    fn validate_cert_query_input(ids: &Option<Vec<String>>, cert_type: &Option<String>) -> Result<(), CertError> {
        // Check if there are more than 100 IDs
        if let Some(ids) = &ids {
            if ids.len() > CertService::MAX_NUMBER_OF_QUERIES {
                error!("IDs exceed maximum limit of 100");
                return Err(CertError::TooManyRequestsError("IDs exceed maximum limit of 100".to_string()));
            }
        }

        // Verify the type field
        if let Some(cert_type) = &cert_type {
            let is_valid = matches!(cert_type.as_str(), 
                CertificateType::REFVALUE | 
                CertificateType::POLICY | 
                CertificateType::TPM_BOOT | 
                CertificateType::TPM_IMA | 
                CertificateType::ASCEND_NPU |
                CertificateType::CRL
            );
            
            if !is_valid {
                error!("Invalid certificate type");
                return Err(CertError::IncorrectFormatError("Invalid certificate type".to_string()));
            }
        }

        Ok(())
    }

    /// Processes a revoked certificate by verifying its signature and updating its status.
    ///
    /// # Arguments
    /// * `tx` - Database transaction.
    /// * `cert` - The certificate model.
    /// * `cert_revoked_model` - The revoked certificate model.
    ///
    /// # Returns
    /// The updated certificate model.
    async fn process_revoked_certificate(
        tx: &DatabaseTransaction,
        mut cert: cert_info::Model,
        cert_revoked_model: &mut cert_revoked_list::Model,
    ) -> cert_info::Model {
        if !Self::verify_revoke_cert_integrity(tx, cert_revoked_model).await {
            cert_revoked_model.valid_code = Some(ValidCode::VERIFICATION_FAILURE);
        }

        // Update certificate information to revoked status
        if !cert.valid_code.eq(&Some(ValidCode::REVOKE)) {
            match CertRepository::update_cert_valid_code(tx, &cert.id, Some(ValidCode::REVOKE)).await {
                Ok(_) => debug!("Successfully updated cert"),
                Err(e) => error!("Failed to update cert: {}", e),
            }
            cert.valid_code = Some(ValidCode::REVOKE);
        }

        cert
    }

    /// Checks if a certificate has expired and updates its status if necessary.
    ///
    /// # Arguments
    /// * `tx` - Database transaction.
    /// * `cert` - The certificate model to check.
    ///
    /// # Returns
    /// The updated certificate model.
    async fn check_certificate_expiration(tx: &DatabaseTransaction, mut cert: cert_info::Model) -> cert_info::Model {
        let timestamp = chrono::Utc::now().timestamp();
        if let Some(cert_content) = cert.cert_info.clone() {
            match parse_cert_content(&String::from_utf8_lossy(&cert_content).as_bytes()) {
                Ok(cert_x509) => {
                    if let Ok(expiration_time) = asn1_time_to_timestamp(cert_x509.not_after()) {
                        if expiration_time < timestamp && cert.valid_code.eq(&Some(ValidCode::NORMAL)) {
                            match CertRepository::update_cert_valid_code(tx, &cert.id, Some(ValidCode::REVOKE)).await {
                                Ok(_) => debug!("Successfully updated cert"),
                                Err(e) => error!("Failed to update cert: {}", e),
                            }
                            cert.valid_code = Some(ValidCode::REVOKE);
                        }
                    } else {
                        error!("Failed to obtain the certificate expiration time.");
                    }
                },
                Err(e) => error!("Failed to parse cert content: {}", e),
            }
        }

        cert
    }

    /// Processes a regular certificate by verifying its signature and checking expiration.
    ///
    /// # Arguments
    /// * `tx` - Database transaction.
    /// * `cert` - The certificate model to process.
    ///
    /// # Returns
    /// The updated certificate model.
    async fn process_regular_certificate(tx: &DatabaseTransaction, mut cert: cert_info::Model) -> cert_info::Model {
        if !Self::verify_cert_integrity(tx, &cert).await {
            cert.valid_code = Some(ValidCode::VERIFICATION_FAILURE);
        } else {
            // Verify if the certificate has expired
            cert = Self::check_certificate_expiration(tx, cert).await;
        }

        cert
    }

    /// Processes certificates by verifying signatures and checking expiration/revocation status.
    ///
    /// # Arguments
    /// * `tx` - Database transaction.
    /// * `certs` - Vector of certificate and optional revoked certificate tuples.
    /// * `ids` - Optional vector of certificate IDs (indicates if this is a specific query).
    ///
    /// # Returns
    /// Vector of processed certificates.
    async fn process_certificates(
        tx: &DatabaseTransaction,
        mut certs: Vec<(cert_info::Model, Option<cert_revoked_list::Model>)>,
        ids: &Option<Vec<String>>,
    ) -> Vec<(cert_info::Model, Option<cert_revoked_list::Model>)> {
        // Only process certificates if this is a specific ID query
        if ids.is_some() {
            for (cert, cert_revoked) in &mut certs {
                if let Some(cert_revoked_model) = cert_revoked {
                    *cert = Self::process_revoked_certificate(tx, cert.clone(), cert_revoked_model).await;
                } else {
                    *cert = Self::process_regular_certificate(tx, cert.clone()).await;
                }
            }
        }

        certs
    }

    /// Retrieves all certificates for a given user, optionally filtered by IDs or type.
    ///
    /// This function handles querying certificates and CRLs, verifying signatures,
    /// checking expiration and revocation status, and updating the database
    /// if the validity code changes.
    ///
    /// # Arguments
    /// * `db` - Database connection pool.
    /// * `ids` - Optional vector of certificate IDs to query.
    /// * `cert_type` - Optional certificate type to filter by ("refvalue", "policy", "tpm_boot", "tpm_ima", "crl").
    /// * `user_id` - The ID of the user whose certificates are being queried.
    ///
    /// # Returns
    /// An `Result<HttpResponse, CertError>` containing the query response or an error.
    pub async fn get_all_certs(
        db: Data<Arc<DatabaseConnection>>,
        ids: &Option<Vec<String>>,
        cert_type: &Option<String>,
        user_id: &str,
    ) -> Result<HttpResponse, CertError> {
        info!("Handling request to get all certs");

        // Validate input parameters
        if let Err(error) = Self::validate_cert_query_input(ids, cert_type) {
            return Err(error.into());
        }

        // Handle CRL queries separately
        if let Some(cert_type) = &cert_type {
            if cert_type == CertificateType::CRL {
                return Self::query_crl_info(db, ids, user_id).await.map_err(|e| {
                    error!("Failed to query CRL info: {:?}", e);
                    CertError::DatabaseOperationError(format!("Failed to query CRL info: {}", e))
                });
            }
        }

        match CertRepository::find_all(&db, ids, &cert_type, user_id).await {
            Ok(certs) => {
                info!("Successfully retrieved certs");
                let tx = match db.begin().await {
                    Ok(tx) => tx,
                    Err(e) => {
                        error!("Failed to get database transaction: {}", e);
                        return Err(CertError::DatabaseOperationError(
                            format!("Failed to get database transaction: {}", e.to_string()),
                        ));
                    },
                };

                // Process certificates (verify signatures, check expiration/revocation)
                let processed_certs = Self::process_certificates(&tx, certs, ids).await;

                if let Err(e) = tx.commit().await {
                    error!("Failed to commit database transaction: {}", e);
                    return Err(CertError::DatabaseOperationError(
                        format!("Failed to commit database transaction: {}", e.to_string()),
                    ));
                }

                Ok(HttpResponse::Ok().json(QueryResponse::from_models(processed_certs)))
            },
            Err(e) => {
                error!("Failed to retrieve certs: {:?}", e);
                Err(CertError::DbError(format!("Failed to retrieve certs: {}", e.to_string())))
            },
        }
    }

    /// Deletes certificates based on the provided delete request.
    ///
    /// Certificates can be deleted by ID, type, or all certificates for the user.
    ///
    /// # Arguments
    /// * `db` - Database connection pool.
    /// * `delete_request` - The request containing deletion criteria (type, IDs, cert_type).
    /// * `user_id` - The ID of the user whose certificates are being deleted.
    ///
    /// # Returns
    /// A `Result<HttpResponse, CertError>` indicating success or failure.
    pub async fn delete_certs(
        db: Data<Arc<DatabaseConnection>>,
        delete_request: DeleteRequest,
        user_id: &str,
    ) -> Result<HttpResponse, CertError> {
        let delete_type = delete_request.delete_type.clone();
        let ids = delete_request.ids.clone();
        let cert_type = delete_request.cert_type.clone();

        match cert_type.as_deref() {
            Some("crl") => {
                Self::handle_crl_deletion(db, ids, user_id).await
            }
            _ => {
                Self::handle_cert_deletion(db, delete_type, ids, cert_type, user_id).await
            }
        }
    }

    async fn handle_crl_deletion(
        db: Data<Arc<DatabaseConnection>>,
        ids: Option<Vec<String>>,
        user_id: &str,
    ) -> Result<HttpResponse, CertError> {
        match CertRepository::delete_crl_info(ids, user_id, &db).await {
            Ok(_) => Ok(HttpResponse::Ok().finish()),
            Err(e) => {
                error!("Failed to delete crl: {:?}", e);
                Err(CertError::DatabaseOperationError(format!("Failed to delete crl: {}", e.to_string())))
            }
        }
    }

    async fn handle_cert_deletion(
        db: Data<Arc<DatabaseConnection>>,
        delete_type: Option<DeleteType>,
        ids: Option<Vec<String>>,
        cert_type: Option<String>,
        user_id: &str,
    ) -> Result<HttpResponse, CertError> {
        // Check if delete_type is set
        if delete_type.is_none() {
            return Err(CertError::IncorrectFormatError("Delete type is empty".to_string()));
        }

        let delete_type = delete_type.unwrap();

        // Parameter validation based on delete type
        match delete_type {
            DeleteType::Id => {
                // Check if IDs are set
                if ids.is_none() {
                    return Err(CertError::IncorrectFormatError("IDs not set".to_string()));
                }
                
                // Check if there are more than 10 IDs
                if let Some(ids) = &ids {
                    if ids.len() > CONFIG.get_instance().unwrap().attestation_service.cert.single_user_cert_limit as usize {
                        return Err(CertError::IncorrectFormatError("IDs exceed maximum limit of 10".to_string()));
                    }
                }
            },
            DeleteType::Type => {
                // Check if certificate type is set
                if cert_type.is_none() {
                    return Err(CertError::IncorrectFormatError("certificate type not set".to_string()));
                }
                
                // Check if the certificate type is legal
                let valid_types = [
                    CertificateType::REFVALUE,
                    CertificateType::POLICY,
                    CertificateType::TPM_BOOT,
                    CertificateType::TPM_IMA,
                    CertificateType::ASCEND_NPU,
                ];
                if let Some(cert_type) = &cert_type {
                    if !valid_types.contains(&cert_type.as_str()) {
                        return Err(CertError::IncorrectFormatError("Invalid certificate type".to_string()));
                    }
                }
            },
            DeleteType::All => {
                // No additional validation needed for delete all
            },
        }

        // Call repository method to delete certificates
        match CertRepository::delete_certs(&db, delete_type, ids, cert_type, user_id).await {
            Ok(_) => Ok(HttpResponse::Ok().finish()),
            Err(e) => {
                error!("Failed to delete certs: {:?}", e);
                Err(CertError::DatabaseOperationError(format!("Failed to delete certs: {}", e.to_string())))
            },
        }
    }

    /// Verify request and add certificate
    ///
    /// Handles the request to add a new certificate or CRL for a user.
    /// Validates the request, parses the content, and inserts the information
    /// into the database.
    ///
    /// # Arguments
    /// * `db` - Database connection pool.
    /// * `request` - The request containing the certificate or CRL data.
    /// * `user_id` - The ID of the user adding the certificate/CRL.
    ///
    /// # Returns
    /// A `Result<HttpResponse, CertError>` indicating success or failure.
    pub async fn add_cert(
        db: Data<Arc<DatabaseConnection>>,
        request: AddCertRequest,
        user_id: &str,
    ) -> Result<HttpResponse, CertError> {
        if let Err(e) = request.validate() {
            error!("Request body is invalidate: {:?}", e);
            return Err(CertError::IncorrectFormatError(format!("Request body is invalidate: {}", e.to_string())));
        }
        // Processing certificate types
        if !request.cert_type.contains(&CertificateType::CRL.to_string()) {
            Self::insert_cert_info(request, user_id, db).await
        } else {
            Self::insert_crl(request, user_id, db).await
        }
    }

    async fn verify_revocation_list(
        request: AddCertRequest,
        user_id: &str,
        db: Data<Arc<DatabaseConnection>>,
    ) -> Result<X509Crl, CertError> {
        // Analyze certificate revocation list
        let crl = match parse_crl_content(&request.crl_content.clone().unwrap()) {
            Ok(crl) => crl,
            Err(e) => {
                error!("Failed to parse CRL content: {:?}", e);
                return Err(CertError::CrlParsingError(format!("Failed to parse CRL content: {}", e.to_string())));
            },
        };

        // Verify that the entries in the revocation list are empty
        if crl.get_revoked().is_none() {
            error!("Failed to get CRL revoked");
            return Err(CertError::CrlParsingError("Failed to get CRL revoked".to_string()));
        }

        // Check the validity period
        if let Some(next_update) = crl.next_update() {
            match Asn1Time::days_from_now(0) {
                Ok(now_time) => {
                    if next_update < now_time {
                        error!("CRL next update time is timeout");
                        return Err(CertError::CrlTimeoutError("CRL next update time is timeout".to_string()));
                    }
                },
                Err(e) => {
                    error!("get now time error: {:?}", e);
                    return Err(CertError::InternalError(format!("get now time error: {}", e.to_string())));
                },
            };
        }

        // Verify the current number of CRLs owned by the user
        match CertRepository::get_user_crl_num(&db, &user_id, request.name.clone()).await {
            Ok(count) => {
                if count >= CONFIG.get_instance().unwrap().attestation_service.cert.single_user_cert_limit {
                    error!("this user's crl has arrived the online limit");
                    return Err(CertError::CrlLimitReached("this user's crl has arrived the online limit".to_string()));
                }
            },
            Err(e) => {
                error!("Failed to get user crl count: {:?}", e);
                return Err(CertError::DatabaseOperationError(format!("Failed to get user crl count: {}", e.to_string())));
            },
        }
        Ok(crl)
    }

    async fn build_insert_crl_info(
        request: AddCertRequest,
        user_id: &str,
        db: Data<Arc<DatabaseConnection>>,
    ) -> Result<(Vec<cert_revoked_list::ActiveModel>, crl_info::ActiveModel), CertError> {
        let crl_content = request.crl_content.clone().unwrap();
        let crl = Self::verify_revocation_list(request.clone(), user_id, db.clone()).await?;
        let crl_id = match CertRepository::get_user_crl_id(&db, user_id, request.name.clone()).await {
            Ok(crl_id) => crl_id,
            Err(e) => {
                error!("Get user crl id error: {:?}", e);
                return Err(CertError::DatabaseOperationError(format!("Get user crl id error: {}", e.to_string())));
            },
        };
        let issuer = get_crl_issuer_name(&crl);
        let mut cert_revoked_list = Vec::new();
        for revoked in crl.get_revoked().unwrap() {
            // Obtain certificate serial number and issuer
            let serial_bn = revoked.serial_number().to_bn().map_err(|_| return "".to_string()).unwrap();
            let serial_num = hex::encode(serial_bn.to_vec());
            // Obtain revocation time
            let revocation_timestamp = match asn1_time_to_timestamp(revoked.revocation_date()) {
                Ok(revocation_timestamp) => revocation_timestamp,
                Err(e) => {
                    error!("Failed to parse CRL revocation date: {:?}", e);
                    return Err(CertError::CrlParsingError(format!("Failed to parse CRL revocation date: {}", e.to_string())));
                },
            };
            // Obtain the reason for revocation
            let reason_code = match revoked.extension::<ReasonCode>() {
                Ok(reason) => match reason {
                    Some(reason) => reason.1.get_i64().unwrap_or(0),
                    None => {
                        error!("this user's revoke certs has exceeded the online limit");
                        return Err(CertError::CrlParsingError("CRL revocation reason code is empty".to_string()));
                    },
                },
                Err(e) => {
                    error!("Failed to parse CRL revocation reason code: {:?}", e);
                    return Err(CertError::CrlParsingError(format!("Failed to parse CRL revocation reason code: {}", e.to_string())));
                },
            };
            // Generate certificate ID
            let cert_id = generate_cert_id(&serial_num, &issuer, &user_id);
            
            // Create model for signature generation
            let cert_revoked_model = cert_revoked_list::Model {
                id: cert_id,
                issuer: Some(issuer.clone()),
                serial_num: Some(serial_num),
                user_id: Some(user_id.to_string()),
                cert_revoked_date: Some(revocation_timestamp),
                cert_revoked_reason: Some(reason_code.to_string()),
                crl_id: crl_id.clone(),
                ..Default::default()
            };
            
            // Sign using key management
            let (signature, key_version) = get_signature(&cert_revoked_model).await;
            
            // Convert Model to ActiveModel and add signature
            let mut cert_revoked = cert_revoked_model.into_active_model();
            cert_revoked.signature = ActiveValue::Set(signature);
            cert_revoked.key_version = ActiveValue::Set(key_version);
            cert_revoked.valid_code = ActiveValue::Set(Some(ValidCode::NORMAL));
            cert_revoked_list.push(cert_revoked);
        }

        // Assemble revocation table data
        let crl_info = crl_info::ActiveModel {
            crl_id: ActiveValue::Set(crl_id.clone()),
            user_id: ActiveValue::Set(user_id.to_string()),
            name: ActiveValue::Set(request.name.clone().to_string()),
            crl_content: ActiveValue::Set(crl_content.into_bytes()),
        };

        Ok((cert_revoked_list, crl_info))
    }

    async fn insert_crl(
        request: AddCertRequest,
        user_id: &str,
        db: Data<Arc<DatabaseConnection>>,
    ) -> Result<HttpResponse, CertError> {
        // Query the revocation list ID corresponding to the database, and if not, randomly generate a UUID
        let (cert_revoked_list, crl_info): (Vec<cert_revoked_list::ActiveModel>, crl_info::ActiveModel) =
            match Self::build_insert_crl_info(request.clone(), user_id, db.clone()).await {
                Ok((cert_revoked_list, crl_info)) => (cert_revoked_list, crl_info),
                Err(e) => return Err(e.into()),
            };
        let tx = match db.begin().await {
            Ok(tx) => tx,
            Err(e) => {
                error!("Failed to get database transaction: {}", e);
                return Err(CertError::DbError(e.to_string()));
            },
        };
        // Delete data from revocation table
        if let Err(e) =
            CertRepository::delete_user_crl_by_ids(&tx, vec![crl_info.crl_id.clone().unwrap()], user_id).await
        {
            error!("Failed to delete crl: {:?}", e);
            if let Err(e) = tx.rollback().await {
                error!("Failed to rollback database transaction: {:?}", e);
            }
            return Err(CertError::DbError(format!("Failed to delete crl: {}", e)));
        }
        // Insert revocation table data
        if let Err(e) = CertRepository::insert_crl_info(&tx, crl_info.clone()).await {
            error!("Failed to insert crl: {:?}", e);
            if let Err(e) = tx.rollback().await {
                error!("Failed to rollback database transaction: {}", e);
            }
            return Err(CertError::DbError(format!("Failed to insert crl: {}", e)));
        }

        for cert_revoked in cert_revoked_list.clone() {
            if let Err(e) = CertRepository::insert_cert_revoked(&tx, cert_revoked).await {
                error!("Failed to insert cert revoked: {:?}", e);
                if let Err(e) = tx.rollback().await {
                    error!("Failed to rollback database transaction: {}", e);
                }
                return Err(CertError::DbError(format!("Failed to insert cert revoked: {}", e)));
            }
        }
        if let Err(e) = tx.commit().await {
            error!("Failed to commit database transaction: {}", e);
            return Err(CertError::DbError(format!("Failed to commit database transaction: {}", e)));
        }

        Ok(HttpResponse::Ok().json(json!({
            "crl":{
                "crl_id": crl_info.crl_id.clone().unwrap().to_string(),
                "crl_name": request.name.clone().to_string(),
            }
        })))
    }

    async fn insert_cert_info(
        request: AddCertRequest,
        user_id: &str,
        db: Data<Arc<DatabaseConnection>>,
    ) -> Result<HttpResponse, CertError> {
        // Analyze certificate content
        let cert_content = request.content.clone().unwrap();
        match parse_cert_content(&cert_content.as_bytes()) {
            Ok(cert) => {
                if !verify_cert(&cert) {
                    error!("The imported certificate is invalid.");
                    return Err(CertError::CertParsingError("The imported certificate is invalid.".to_string()));
                }
                
                // Extract certificate information
                let serial_num = get_cert_serial_number(&cert);
                let issuer = get_cert_issuer_name(&cert);
                let owner = get_cert_subject_name(&cert);
                let cert_id = generate_cert_id(&serial_num, &issuer, &user_id);
                let timestamp_millis = chrono::Utc::now().timestamp_millis();
                
                // Create model for signature generation
                let mut cert_model = cert_info::Model::from_add_cert_request_for_signature(
                    &request,
                    cert_id.clone(),
                    serial_num.clone(),
                    user_id.to_string(),
                    issuer.clone(),
                    owner.clone(),
                    cert_content.clone().into_bytes(),
                    timestamp_millis,
                );
                
                // Generate signature
                let (signature, key_version) = get_signature(&cert_model).await;
                
                // Update model with signature information and convert to ActiveModel
                cert_model.signature = signature;
                cert_model.key_version = key_version;
                cert_model.valid_code = Some(ValidCode::NORMAL);
                let cert_info = cert_model.into_active_model();

                // Insert certificate information
                match CertRepository::insert_cert_info(
                    &db,
                    cert_info,
                    CONFIG.get_instance().unwrap().attestation_service.cert.single_user_cert_limit,
                )
                .await
                {
                    Ok(count) => {
                        if count == 0 {
                            error!(
                                    "User has reached the maximum number of cert or cert name or cert is exist, please retry!"
                                );
                            return Err(CertError::CertLimitReached("User has reached the maximum number of cert or cert name or cert is exist, please retry!".to_string()));
                        }
                        Ok(HttpResponse::Ok().json(AddCertResponse {
                            cert: Some(CertRespInfo {
                                cert_id: Some(cert_id),
                                cert_name: Some(request.name.clone()),
                                version: Some(1),
                                ..Default::default()
                            }),
                            ..Default::default()
                        }))
                    },
                    Err(e) => {
                        error!("Failed to insert cert info: {:?}", e);
                        Err(CertError::DbError(format!("Failed to insert cert info: {}", e)))
                    },
                }
            },
            Err(e) => {
                error!("Failed to parse certificate content: {:?}", e);
                Err(CertError::CertParsingError(format!("Failed to parse certificate content: {}", e)))
            },
        }
    }

    /// Validates the update certificate request
    ///
    /// # Arguments
    /// * `db` - Database connection pool
    /// * `request` - The update certificate request to validate
    /// * `user_id` - The ID of the user making the request
    ///
    /// # Returns
    /// `Result<(), HttpResponse>` - Ok if validation passes, Err with error response if validation fails
    async fn validate_update_request(
        db: &Data<Arc<DatabaseConnection>>,
        request: &UpdateCertRequest,
        user_id: &str,
    ) -> Result<(), CertError> {
        // Basic request validation
        if let Err(e) = request.validate() {
            error!("Request body is invalidate: {:?}", e);
            return Err(CertError::IncorrectFormatError(format!("Request body is invalidate: {}", e.to_string())));
        }

        // Check if there are fields to update
        if !request.validate_cert_update_body() {
            error!("there is no field need to be updated");
            return Err(CertError::IncorrectFormatError("there is no field need to be updated".to_string()));
        }

        // Check for name duplication if name is being updated
        if request.name.is_some() {
            match CertRepository::verify_name_is_duplicated(db, request.name.clone(), Some(request.id.clone()), user_id)
                .await
            {
                Ok(is_exist) => {
                    if is_exist {
                        error!("Name is duplicated");
                        return Err(CertError::IncorrectFormatError("Name is duplicated".to_string()));
                    }
                },
                Err(e) => {
                    error!("Failed to verify name is duplicated: {:?}", e);
                    return Err(CertError::DatabaseOperationError(format!("Failed to verify name is duplicated: {}", e.to_string())));
                },
            }
        }

        Ok(())
    }

    /// Checks user permissions for updating a certificate
    ///
    /// # Arguments
    /// * `db` - Database connection pool
    /// * `cert_id` - The ID of the certificate to update
    /// * `user_id` - The ID of the user making the request
    ///
    /// # Returns
    /// `Result<cert_info::Model, HttpResponse>` - Ok with certificate model if permission granted, Err with error response if denied
    async fn check_cert_exists(
        db: &Data<Arc<DatabaseConnection>>,
        cert_id: &str,
        user_id: &str,
    ) -> Result<cert_info::Model, CertError> {
        match CertRepository::find_cert_by_id_and_user(db, &cert_id.to_string(), user_id).await {
            Ok(cert_info_opt) => match cert_info_opt {
                Some(cert_info_model) => Ok(cert_info_model),
                None => {
                    error!("No corresponding certificate found for user {} and cert_id {}", user_id, cert_id);
                    Err(CertError::IncorrectFormatError(
                        "No corresponding certificate found".to_string(),
                    ))
                },
            },
            Err(e) => {
                error!("Database error when finding certificate for user {} and cert_id {}: {}", user_id, cert_id, e);
                Err(CertError::DatabaseOperationError(
                    format!("No corresponding certificate found {}", e.to_string()),
                ))
            },
        }
    }

    /// Updates the certificate model with new values from the request
    ///
    /// # Arguments
    /// * `cert_info_model` - The existing certificate model
    /// * `request` - The update request containing new values
    ///
    /// # Returns
    /// `(cert_info::ActiveModel, cert_info::Model)` - Tuple of ActiveModel for database update and Model for signature
    fn update_cert_model(
        cert_info_model: &cert_info::Model,
        request: &UpdateCertRequest,
    ) -> (cert_info::ActiveModel, cert_info::Model) {
        let timestamp_millis = chrono::Utc::now().timestamp_millis();
        let new_version = cert_info_model.version.unwrap_or(1) + 1;

        // Start with the original model and apply updates
        let mut cert_model_sig = cert_info_model.clone();
        let mut cert_info: cert_info::ActiveModel = cert_info_model.clone().into();

        // Apply updates from request
        if let Some(ref name) = request.name {
            cert_model_sig.name = Some(name.clone());
            cert_info.name = ActiveValue::Set(cert_model_sig.name.clone());
        }
        
        if let Some(ref description) = request.description {
            cert_model_sig.description = Some(description.clone());
            cert_info.description = ActiveValue::Set(cert_model_sig.description.clone());
        }
        
        if let Some(ref cert_type) = request.cert_type {
            cert_model_sig.cert_type = Some(json!(cert_type));
            cert_info.cert_type = ActiveValue::Set(cert_model_sig.cert_type.clone());
        }
        
        if let Some(is_default) = request.is_default {
            cert_model_sig.is_default = Some(is_default);
            cert_info.is_default = ActiveValue::Set(cert_model_sig.is_default.clone());
        }

        // Update version and timestamp
        cert_model_sig.version = Some(new_version);
        cert_model_sig.update_time = Some(timestamp_millis);
        cert_info.version = ActiveValue::Set(cert_model_sig.version.clone());
        cert_info.update_time = ActiveValue::Set(cert_model_sig.update_time.clone());

        cert_model_sig.signature = None;
        cert_model_sig.key_version = None;
        cert_model_sig.key_id = None;
        cert_model_sig.valid_code = None;

        (cert_info, cert_model_sig)
    }

    /// Saves the updated certificate to the database using a transaction
    ///
    /// # Arguments
    /// * `tx` - Database transaction
    /// * `request` - The update request
    /// * `cert_info` - The updated ActiveModel to save
    /// * `cert_model_sig` - The model for signature generation
    ///
    /// # Returns
    /// `Result<HttpResponse, CertError>` - Success or error response
    async fn save_updated_cert(
        tx: &DatabaseTransaction,
        request: &UpdateCertRequest,
        mut cert_info: cert_info::ActiveModel,
        cert_model_sig: &cert_info::Model,
    ) -> Result<HttpResponse, CertError> {
        // Sign using key management
        let (signature, key_version) = get_signature(cert_model_sig).await;
        cert_info.signature = ActiveValue::Set(signature);
        cert_info.key_version = ActiveValue::Set(key_version);

        let version = cert_model_sig.version.clone().unwrap_or(1) - 1;

        match CertRepository::update_cert_info_when_signature_update(tx, &request.id, version, cert_info)
            .await
        {
            Ok(res) => {
                if res.rows_affected == 1 {
                    // Return successful response
                    Ok(HttpResponse::Ok().json(AddCertResponse {
                        cert: Some(CertRespInfo {
                            cert_id: Some(request.id.clone()),
                            cert_name: request.name.clone(),
                            version: Some(cert_model_sig.version.clone().unwrap_or(1)),
                            ..Default::default()
                        }),
                        ..Default::default()
                    }))
                } else {
                    error!("Certificate has been modified by another request, please retry");
                    Err(CertError::IncorrectFormatError("Certificate has been modified by another request, please retry".to_string()))
                }
            },
            Err(e) => {
                error!("Certificate update failure {}", e);
                Err(CertError::DbError(format!("Certificate update failure {}", e)))
            },
        }
    }

    /// Verify requests and update certificates
    ///
    /// Handles the request to update an existing certificate for a user.
    /// Validates the request, checks user permissions, updates the certificate
    /// information in the database, and re-signs the updated certificate model.
    ///
    /// # Arguments
    /// * `db` - Database connection pool.
    /// * `request` - The request containing the updated certificate data.
    /// * `user_id` - The ID of the user updating the certificate.
    ///
    /// # Returns
    /// An `actix_web::Result<HttpResponse>` indicating success or failure.
    pub async fn update_cert(
        db: Data<Arc<DatabaseConnection>>,
        request: UpdateCertRequest,
        user_id: String,
    ) -> Result<HttpResponse, CertError> {
        let tx = db.begin().await.map_err(|e| CertError::DbError(e.to_string()))?;

        if let Err(error) = Self::validate_update_request(&db, &request, &user_id).await {
            return Err(error.into());
        }

        let cert_info_model = match Self::check_cert_exists(&db, &request.id, &user_id).await {
            Ok(model) => model,
            Err(error) => return Err(error.into()),
        };

        if !Self::verify_cert_integrity(&tx, &cert_info_model).await {
            tx.commit().await.map_err(|e| CertError::DbError(e.to_string()))?;
            return Err(CertError::CertSignatureVerificationError("Certificate integrity verification failed".to_string()));
        }

        let (cert_info, cert_model_sig) = Self::update_cert_model(&cert_info_model, &request);

        let result = Self::save_updated_cert(&tx, &request, cert_info, &cert_model_sig).await;
        
        match result {
            Ok(response) => {
                tx.commit().await.map_err(|e| CertError::DbError(e.to_string()))?;
                Ok(response)
            }
            Err(error) => {
                tx.rollback().await.map_err(|e| CertError::DbError(e.to_string()))?;
                Err(error)
            }
        }
    }

    /// Verifies the signature of a certificate model and updates its status if verification fails.
    ///
    /// This function prepares the certificate model by clearing signature and key information
    /// before verifying the signature against the stored signature and key version.
    /// If the signature is invalid and the certificate's current status is `NORMAL`,
    /// its status is updated to `VERIFICATION_FAILURE`.
    ///
    /// # Arguments
    /// * `db` - A reference to the database transaction.
    /// * `cert` - A reference to the `cert_info::Model` to verify.
    ///
    /// # Returns
    /// `true` if the signature verification is successful, `false` otherwise.
    async fn verify_cert_integrity(db: &DatabaseTransaction, cert: &cert_info::Model) -> bool {
        let mut cert_sig = cert.clone();
        cert_sig.signature = None;
        cert_sig.key_version = None;
        cert_sig.key_id = None;
        cert_sig.valid_code = None;
        let is_integrity = verify_signature(&cert_sig, cert.signature.clone(), cert.key_version.clone()).await;
        if !is_integrity && cert.valid_code.eq(&Some(ValidCode::NORMAL)) {
            match CertRepository::update_cert_valid_code(&db, &cert.id, Some(ValidCode::VERIFICATION_FAILURE)).await {
                Ok(_) => info!("Successfully updated cert"),
                Err(e) => error!("Failed to update cert: {}", e),
            }
        }
        is_integrity
    }

    /// Verifies the signature of a revoked certificate model and updates its status if verification fails.
    ///
    /// This function prepares the revoked certificate model by clearing signature and key information
    /// before verifying the signature against the stored signature and key version.
    /// If the signature is invalid and the revoked certificate's current status is `NORMAL`,
    /// its status is updated to `VERIFICATION_FAILURE`.
    ///
    /// # Arguments
    /// * `db` - A reference to the database transaction.
    /// * `cert_revoked_model` - A reference to the `cert_revoked_list::Model` to verify.
    ///
    /// # Returns
    /// `true` if the signature verification is successful, `false` otherwise.
    async fn verify_revoke_cert_integrity(
        db: &DatabaseTransaction,
        cert_revoked_model: &cert_revoked_list::Model,
    ) -> bool {
        let mut cert_sig = cert_revoked_model.clone();
        cert_sig.signature = None;
        cert_sig.key_version = None;
        cert_sig.key_id = None;
        cert_sig.valid_code = None;
        let is_integrity =
            verify_signature(&cert_sig, cert_revoked_model.signature.clone(), cert_revoked_model.key_version.clone())
                .await;
        if !is_integrity && cert_revoked_model.valid_code.eq(&Some(ValidCode::NORMAL)) {
            match CertRepository::update_cert_revoked_valid_code(
                &db,
                &cert_revoked_model.id,
                Some(ValidCode::VERIFICATION_FAILURE),
            )
            .await
            {
                Ok(_) => debug!("Successfully updated cert revoked"),
                Err(e) => error!("Failed to update cert revoked: {}", e),
            }
        }
        is_integrity
    }

    async fn get_valid_certs_for_verification(
        cert_type: &str,
        user_id: &str,
    ) -> Result<Vec<cert_info::Model>, CertVerifyError> {
        if cert_type.is_empty() && user_id.is_empty() {
            error!("The cert_type or user_id is empty");
            return Err(CertVerifyError::VerifyError("cert_type or user_id is empty".to_string()));
        }

        info!("Begin getting valid certificates for verification, user_id: {}, cert_type: {}", user_id, cert_type);

        let db = get_connection().await.map_err(|e| {
            error!("Failed to get database connection: {}", e);
            CertVerifyError::DbError(e.to_string())
        })?;
        let db = db.as_ref();

        let cert_data = CertRepository::find_certs_by_type_and_user(db, user_id, cert_type).await.map_err(|e| {
            error!("Failed to query certificate by type and user: {:?}", e);
            CertVerifyError::DbError(e.to_string())
        })?;

        if cert_data.is_empty() {
            error!("The certificate queried is empty");
            return Err(CertVerifyError::VerifyError("No certificates found".to_string()));
        }

        let tx = db.begin().await.map_err(|e| {
            error!("Failed to get database transaction: {}", e);
            CertVerifyError::DbError(e.to_string())
        })?;

        let certs: Vec<cert_info::Model> = Self::filter_invalid_cert(&tx, cert_data).await;

        tx.commit().await.map_err(|e| {
            error!("Failed to commit database transaction: {}", e);
            CertVerifyError::DbError(e.to_string())
        })?;

        if certs.is_empty() {
            error!("All certificates queried have been revoked or tampered with");
            return Err(CertVerifyError::VerifyError("All certificates are invalid".to_string()));
        }

        Ok(certs)
    }

    async fn filter_invalid_cert(
        db: &DatabaseTransaction,
        certs: Vec<(cert_info::Model, Option<cert_revoked_list::Model>)>,
    ) -> Vec<cert_info::Model> {
        stream::iter(certs.into_iter())
            .filter_map(|(cert, revoke_cert)| async move {
                if revoke_cert.is_some() {
                    let revoke_is_valid = Self::verify_revoke_cert_integrity(db, &revoke_cert.unwrap()).await;
                    if revoke_is_valid {
                        if cert.valid_code.eq(&Some(ValidCode::NORMAL)) {
                            match CertRepository::update_cert_valid_code(&db, &cert.id, Some(ValidCode::REVOKE)).await {
                                Ok(_) => debug!("Successfully updated cert revoked"),
                                Err(e) => error!("Failed to update cert revoked: {}", e),
                            }
                        }
                        return None;
                    }
                }
                let cert_is_valid = Self::verify_cert_integrity(db, &cert).await;
                if !cert_is_valid {
                    return None;
                }
                Some(cert)
            })
            .collect::<Vec<_>>()
            .await
    }

    /// Verifies a single certificate against the provided signature and data.
    ///
    /// This method encapsulates the logic for verifying a single certificate, including:
    /// - Parsing the certificate content
    /// - Validating certificate expiration time
    /// - Creating and using a verifier to check the signature
    ///
    /// # Arguments
    /// * `cert_info` - The certificate information as a byte slice
    /// * `signature` - The signature to verify
    /// * `alg` - The message digest algorithm to use
    /// * `data` - The data that was signed
    ///
    /// # Returns
    /// * `Ok(true)` if the certificate successfully verifies the signature
    /// * `Ok(false)` if the certificate fails to verify the signature
    /// * `Err(CertVerifyError)` if there's an error during verification
    async fn verify_single_certificate(
        cert_info: &[u8],
        signature: &[u8],
        alg: MessageDigest,
        data: &[u8],
    ) -> Result<bool, CertVerifyError> {
        match parse_cert_content(cert_info) {
            Ok(cert) => {
                info!("Begin verify signature {}", get_cert_serial_number(&cert));

                // Check certificate expiration
                if !verify_cert_time(&cert) {
                    error!("The parent certificate is expired");
                    return Ok(false);
                }

                // Obtain certificate public key
                let pub_key = cert.public_key().unwrap();

                // Create verifier
                let mut verifier = match Verifier::new(alg, &pub_key) {
                    Ok(verifier) => verifier,
                    Err(e) => {
                        error!("Failed to get verifier: {}", e);
                        return Ok(false);
                    },
                };

                // Verify certificate signature
                if let Err(e) = verifier.update(data) {
                    error!("Failed to update data: {}", e);
                    return Ok(false);
                }

                match verifier.verify(signature) {
                    Ok(is_valid) => {
                        if is_valid {
                            info!("Successfully verified certificate signature");
                            Ok(true)
                        } else {
                            error!("Failed verified certificate signature");
                            Ok(false)
                        }
                    },
                    Err(e) => {
                        error!("Verified certificate signature error: {}", e);
                        Ok(false)
                    },
                }
            },
            Err(e) => {
                error!("Parse cert content error: {}", e);
                Ok(false)
            },
        }
    }

    /// Verifies a signature against a user's certificate(s) of a specific type.
    ///
    /// This function retrieves valid certificates for the given user and type,
    /// then attempts to verify the provided signature and data using the public
    /// key from each valid certificate.
    ///
    /// # Arguments
    /// * `cert_type` - The type of the certificate to use for verification.
    /// * `user_id` - The ID of the user whose certificate is being used.
    /// * `signature` - The signature to verify.
    /// * `alg` - The message digest algorithm used for signing.
    /// * `data` - The original data that was signed.
    ///
    /// # Returns
    /// A `Result` indicating whether the signature was successfully verified
    /// against any valid certificate (`Ok(true)`), if no valid certificate
    /// was found or none verified the signature (`Ok(false)`), or if an
    /// error occurred during the process (`Err(CertVerifyError)`).
    pub async fn verify_by_cert(
        cert_type: &str,
        user_id: &str,
        signature: &[u8],
        alg: MessageDigest,
        data: &[u8],
    ) -> Result<bool, CertVerifyError> {
        let certs = match Self::get_valid_certs_for_verification(cert_type, user_id).await {
            Ok(certs) => certs,
            Err(_) => {
                return Ok(false);
            },
        };

        for model in certs.into_iter() {
            let cert_info = model.cert_info.unwrap();
            match Self::verify_single_certificate(&cert_info, signature, alg, data).await {
                Ok(true) => {
                    info!("Successfully verified certificate signature");
                    return Ok(true);
                },
                Ok(false) => {
                    error!("Failed verified certificate signature");
                    continue;
                },
                Err(e) => {
                    error!("Certificate verification error: {:?}", e);
                    continue;
                },
            }
        }
        Ok(false)
    }

    /// Initializes the certificate chain verification by getting database connection
    /// and parsing the initial certificate.
    ///
    /// # Arguments
    /// * `cert` - The byte slice containing the certificate content (DER or PEM format).
    ///
    /// # Returns
    /// A `Result` containing the database connection and parsed certificate,
    /// or an error if initialization fails.
    async fn initialize_cert_chain_verification(
        cert: &[u8],
    ) -> Result<(Arc<DatabaseConnection>, X509), CertVerifyError> {
        let db = get_connection().await.map_err(|e| {
            error!("Failed to get database connection: {}", e);
            CertVerifyError::DbError(e.to_string())
        })?;

        let agent_cert = parse_cert_content(&cert).map_err(|e| {
            error!("Failed to parse cert to X509: {}", e);
            CertVerifyError::VerifyError(e.to_string())
        })?;

        info!("Begin verify certificate chain {:?}", agent_cert.subject_name());

        if !verify_cert_time(&agent_cert) {
            error!("The certificate has expired");
            return Err(CertVerifyError::VerifyError("The certificate has expired".to_string()));
        }

        Ok((db, agent_cert))
    }

    /// Finds and filters valid parent certificates for the given certificate.
    ///
    /// # Arguments
    /// * `db` - The database connection.
    /// * `user_id` - The ID of the user associated with the certificate chain.
    /// * `cert_type` - The type of the certificate chain to verify.
    /// * `issuer_name` - The issuer name of the certificate to find parents for.
    ///
    /// # Returns
    /// A `Result` containing a vector of valid parent certificates,
    /// or an error if the operation fails.
    async fn find_valid_parent_certificates(
        db: &DatabaseConnection,
        user_id: &str,
        cert_type: &str,
        issuer_name: &str,
    ) -> Result<Vec<cert_info::Model>, CertVerifyError> {
        let certs: Vec<cert_info::Model> =
            match CertRepository::find_parent_cert_by_type_and_user(db, user_id, cert_type, issuer_name).await {
                Ok(certs) => {
                    if certs.is_empty() {
                        error!("The certificate parent certificates is empty for issuer: {}", issuer_name);
                        return Ok(Vec::new());
                    }
                    let tx = db.begin().await.map_err(|e| {
                        error!("Failed to get database transaction, {}", e);
                        CertVerifyError::DbError(e.to_string())
                    })?;
                    let certs = Self::filter_invalid_cert(&tx, certs).await;
                    tx.commit().await.map_err(|e| {
                        error!("Failed to commit transaction: {}", e);
                        CertVerifyError::DbError(e.to_string())
                    })?;
                    certs
                },
                Err(e) => {
                    error!("Failed to query certs by type and user: {:?}", e);
                    return Err(CertVerifyError::DbError(e.to_string()));
                },
            };

        if certs.is_empty() {
            error!("All parent certificates of issuer {} have been revoked or tampered with", issuer_name,);
        }

        Ok(certs)
    }

    /// Verifies a single certificate against its potential parent certificates.
    ///
    /// # Arguments
    /// * `agent_cert` - The certificate to verify.
    /// * `parent_certs` - The potential parent certificates.
    ///
    /// # Returns
    /// A `Result` containing the verified parent certificate if successful,
    /// or `None` if no valid parent is found, or an error if verification fails.
    async fn verify_against_parent_certificates(
        agent_cert: &X509,
        parent_certs: Vec<cert_info::Model>,
    ) -> Result<Option<X509>, CertVerifyError> {
        for model in parent_certs.into_iter() {
            let cert_info = model.cert_info.unwrap();
            match parse_cert_content(&cert_info) {
                Ok(parent_cert) => {
                    info!(
                        "Begin verify certificate chain {} {}",
                        get_cert_serial_number(&agent_cert),
                        get_cert_serial_number(&parent_cert)
                    );
                    if !verify_cert_time(&parent_cert) {
                        error!("The parent certificate is expired");
                        continue;
                    }
                    let parent_pub_key = parent_cert.public_key().unwrap();
                    match agent_cert.verify(&parent_pub_key) {
                        Ok(is_success) => {
                            if !is_success {
                                error!("Verify chain failed");
                            } else {
                                info!("Verify chain success");
                                return Ok(Some(parent_cert));
                            }
                        },
                        Err(e) => {
                            error!("Verify chain occur error: {}", e);
                        },
                    }
                },
                Err(e) => {
                    error!("Parse parent certificate occur error: {}", e);
                    continue;
                },
            }
        }
        Ok(None)
    }

    /// Verifies the certificate chain for a given certificate.
    ///
    /// This function attempts to build and verify the certificate chain starting
    /// from the provided certificate (`cert`). It retrieves parent certificates
    /// from the database based on the issuer name, user ID, and certificate type,
    /// and verifies the signature of each certificate against its issuer's public key.
    /// It also checks the validity period and revocation status of each certificate
    /// in the chain.
    ///
    /// # Arguments
    /// * `cert_type` - The type of the certificate chain to verify.
    /// * `user_id` - The ID of the user associated with the certificate chain.
    /// * `cert` - The byte slice containing the certificate content (DER or PEM format).
    ///
    /// # Returns
    /// A `Result` indicating whether the certificate chain is valid (`Ok(true)`),
    /// invalid or incomplete (`Ok(false)`), or if an error occurred during the
    /// verification process (`Err(CertVerifyError)`).
    pub async fn verify_cert_chain(cert_type: &str, user_id: &str, cert: &[u8]) -> Result<bool, CertVerifyError> {
        // Validate input parameters
        if cert_type.is_empty() && user_id.is_empty() {
            error!("The cert_type or user_id is empty");
            return Err(CertVerifyError::VerifyError("The cert_type or user_id is empty".to_string()));
        }

        // Initialize database connection and parse initial certificate
        let (db, mut agent_cert) = Self::initialize_cert_chain_verification(cert).await?;
        let db = db.as_ref();

        // Traverse the certificate chain until we reach the root certificate
        while get_cert_issuer_name(&agent_cert) != get_cert_subject_name(&agent_cert) {
            // Find valid parent certificates
            let parent_certs =
                Self::find_valid_parent_certificates(db, user_id, cert_type, &get_cert_issuer_name(&agent_cert))
                    .await?;

            if parent_certs.is_empty() {
                error!(
                    "All parent certificates of this certificate {:?} have been revoked or tampered with",
                    agent_cert.subject_name(),
                );
                return Ok(false);
            }

            // Verify against parent certificates
            match Self::verify_against_parent_certificates(&agent_cert, parent_certs).await? {
                Some(parent_cert) => {
                    agent_cert = parent_cert;
                },
                None => {
                    error!("Not find the certificate {} parent certificate", get_cert_serial_number(&agent_cert));
                    return Ok(false);
                },
            }
        }

        info!("Certificate chain verification successful");
        Ok(true)
    }
}
